package com._58city.spark.app;


import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com._58city.spark.app.dao.CPCClickDto;
import com._58city.spark.app.dao.CPCDisplayDto;
import com._58city.spark.app.dao.IMCInfoAddDto;
import com._58city.spark.app.dao.TrackDto;
import com._58city.spark.app.ext.JsonUtil;
import com.alibaba.fastjson.JSONObject;


public class DaoUtil {
	
	private static Logger log = LoggerFactory.getLogger(DaoUtil.class);
	
	public static TrackDto track_app(String txt){
		String[] array = StringUtils.split(txt, TrackDto.SPLIT);
		if (array == null) {
			log.error("track app string is error! (txt : "+ txt+")");
			return null;
		}
		try {
			TrackDto res = new TrackDto();
			res.setPlatform(2);
			res.setCatePath(array[6]);
			res.setPageType(array[9]);
			String tmp = array[11];
			String catePath = res.getCatePath();
			if("-".equals(catePath.trim())||StringUtils.isBlank(catePath)||
					",".equals(catePath)) catePath = "-1";
			if(StringUtils.isNotBlank(catePath)){
				long cateId = -1;
				try {
					cateId = Long.valueOf(catePath.substring(catePath.lastIndexOf(",")+1));
				} catch (Exception e) {
					cateId = -1;
				}
				res.setLastCateId(cateId);
			}
			if(StringUtils.isNotBlank(tmp) && tmp.contains("pagetype")){
				String pagetype = StringUtils.substringBetween(tmp, "\"pagetype\":\"", "\",");
				if(StringUtils.isNotBlank(pagetype)) res.setPageType(pagetype);
			}
			return res;
		} catch (Exception e) {
			log.error("track app string is error! (txt : "+ txt+")");
			return null;
		}
	}
	
	/*
	 * 收到的消息已经是json格式，直接从里面取需要的字段
	 */
	public static TrackDto track(String txt){
		TrackDto dto = new TrackDto();
		JSONObject jsonLog = JSONObject.parseObject(txt);
		
		dto.setCookie(jsonLog.getString("cookieID"));
		dto.setUrl(jsonLog.getString("url"));
		dto.setPageType(jsonLog.getString("pageType"));
		String bizName = jsonLog.getString("bizName");
		if(StringUtils.isBlank(bizName)){
			dto.setBusiLine("other");
		}else{
			dto.setBusiLine(bizName);
		}
		
		String catePath = jsonLog.getString("catePath");
		dto.setCatePath(catePath);
		dto.setLastCateId(-1);
		
		if(StringUtils.isNotBlank(catePath)){
			String lastCate = catePath.substring(catePath.lastIndexOf(",")+1).trim();
			if(NumberUtils.isNumber(lastCate)){
				dto.setLastCateId(Long.valueOf(lastCate));
			}else{
//				log.error("cate is error:"+catePath);
			}
		}
		return dto;
	}
	
//	public static TrackDto track(String txt){
//		TrackDto dto = new TrackDto();
//		JSONObject jsonLog = JSONObject.parseObject(txt);
//		JSONObject trackurlJSON = JSONObject.parseObject(jsonLog.getString("trackUrl"));
//		
//		dto.setCookie(jsonLog.getString("cookieID"));
//		dto.setUrl(jsonLog.getString("url"));
//		dto.setPageType(jsonLog.getString("pageType"));
//		
//		dto.setLastCateId(-1);
//		if(trackurlJSON !=null ){
//			String catePath = trackurlJSON.getString("cate");
//			if(StringUtils.isNotBlank(catePath)){
//				dto.setCatePath(catePath);
//				String lastCate = catePath.substring(catePath.lastIndexOf(",")+1).trim();
//				if(StringUtils.isNumeric(lastCate)){
//					dto.setLastCateId(Long.valueOf(lastCate));
//				}else{
//					log.error("cate is error:"+trackurlJSON);
//				}
//			}
//			if(dto.getPageType() == null)
//				dto.setPageType(trackurlJSON.getString("pagetype"));
//		}
//		return dto;
//	}
	
	// 解析trackurl
	@SuppressWarnings({ "unchecked", "unused" })
	private static Map<String,String> parseTrackUrl(String initialTrackURL) {
		String trackUrl = initialTrackURL;
		trackUrl = trackUrl.trim().replace("%7B", "{").replace("%7D", "}")
				.replace("%7b", "{").replace("%7d", "}").replace(" ", "")
				.replace("，", ",").replace("｛", "{").replace("｝", "}")
				.replace("：", ":").replace("‘", "'").replace("’", "'")
				.replace("%27", "'").replace("%22", "\"").replace("%20", "").replace("':'", "\001")
				.replace("','", "\002").replace("':", "':'")
				.replace(",'", "','").replace("\001", "':'")
				.replace("\002", "','").replace(":'}", "''}");
		if(!trackUrl.endsWith("'}") && !trackUrl.endsWith("\"}") && !trackUrl.endsWith("'")){
			trackUrl += "'}";
		}
		if(!trackUrl.endsWith("}")){
			trackUrl += "}";
		}
		char tmpChar = trackUrl.charAt(trackUrl.length() - 2);
		if (tmpChar != 39 && tmpChar !=  '"'){ //倒数第二个不是单引号
			trackUrl = trackUrl.substring(0, trackUrl.length() - 1)+"'}";
		}
		try {
			return (Map<String,String>)JsonUtil.fromJson(trackUrl, Map.class);
		} catch (Exception e) {
			log.error("parseTrackUrl ERROR the trackUrl is : " +trackUrl);
		}
			return null;
		}
		
	public static CPCDisplayDto cpc_display(String txt){
		String[] array = StringUtils.split(txt, CPCDisplayDto.SPLIT);
		if (array == null) {
			log.error("CPC display string is error! (txt : "+ txt+")");
			return null;
		}
		try {
			return new CPCDisplayDto(array);
		} catch (Exception e) {
			log.error("CPC display string is error! (txt : "+ txt+")");
			return null;
		}
		
	}
	
	public static CPCClickDto cpc_click(String txt){
		String[] array = StringUtils.split(txt, CPCClickDto.SPLIT);
		if (array == null) {
			log.error("CPC click string is error! (txt : "+ txt+")");
			return null;
		}
		try {
			return new CPCClickDto(array);
		} catch (Exception e) {
			log.error("CPC click string is error! (txt : "+ txt+")");
			return null;
		}
		
	}
	
	
	public static IMCInfoAddDto imc_add(String txt){
//		String[] array = StringUtils.split(txt, IMCInfoAddDto.SPLIT);
		String[] array = txt.split(IMCInfoAddDto.SPLIT);
		
		if (array == null) {
			log.error("imc_add string is error! (txt : "+ txt+")");
			return null;
		}
		try {
			return new IMCInfoAddDto(array);
		} catch (Exception e) {
			log.error("imc_add string is error! (txt : "+ txt+")");
			return null;
		}
		
	}
	

}
